package com.dacool.view;

import static com.dacool.util.ViewUtils.rp;

import java.util.ArrayList;

import com.dacool.util.ViewUtils;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

public class TabBar extends LinearLayout {

	private TabSelectionListener mListener;
	private ArrayList<TabItem> mItems;
	private int currentTab = -1;

	public void setTabSelectionListener(TabSelectionListener listener) {
		mListener = listener;
	}

	public TabBar(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}

	public TabBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.setOrientation(LinearLayout.HORIZONTAL);
		mItems = new ArrayList<TabItem>();
	}

	public void addTab(TabItem item) {
		mItems.add(item);
		item.customView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mListener != null) {
					for (int i = 0; i < mItems.size(); i++) {
						TabItem item = mItems.get(i);
						if (item.customView == v) {
							if (mListener == null
									|| mListener.shouldSelectTab(i))
								setCurrentTab(i);
							return;
						}

					}

				}
			}
		});
		LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT);
		lp.weight = 1;
		lp.setMargins(0, rp(3), 0, rp(3));
		this.addView(item.customView, lp);
		this.invalidate();
	}

	public void setCurrentTab(int index) {
		if (currentTab == index)
			return;
		for (int i = 0; i < mItems.size(); i++) {
			TabItem item = mItems.get(i);
			item.customView.setSelected(i == index);
		}
		currentTab = index;
		if (mListener != null) {
			mListener.didSelectTab(currentTab);
		}
	}

	public int getCurrentTab() {
		return currentTab;
	}

	public void setBadgeValue(final int index, final String value) {
		
		ViewUtils.runInMainThread(new Runnable() {
			
			@Override
			public void run() {
				TabItem item = mItems.get(index);
				item.setBadgeValue(value);
			}
		});
	}

	public static interface TabSelectionListener {
		public void didSelectTab(int index);

		public boolean shouldSelectTab(int index);
	}
}
